<template>
  <div class="chuantu" style="position: relative;">
    <el-upload class="avatar-uploader " action="#" :on-change="uploadok" :auto-upload="false" style="width: 100%; height: 100%; border: 1px #ccc solid;" :show-file-list="false" >
      <div class="flexcc" style="width: 100%; height: 100%; color: #666;" v-if="!imgurl">{{wenzi}}</div>
      <div class="flexcc" style="width: 100%; height: 100%;" v-if="imgurl"><img :src="imgurl" style="max-width: 100%; max-height: 100%;" ></div>
    </el-upload>
  </div>
</template>

<script>
  import axios from "axios";
  export default {
    name: 'chuantu',
    props:['imgid','zi'],
    data() {
      return {
        imgurl:"",
        wenzi:"上传"
      }
    },
    created() {
      if(this.imgid){
        this.imgurl = this.IP_URL+'/getimage?imgid='+this.imgid
      }
      if(this.zi){
        this.wenzi = this.zi
      }
    },
    methods: {
      getBase64(file) {
        return new Promise(function (resolve, reject) {
          const reader = new FileReader();
          let imgResult = "";
          reader.readAsDataURL(file);
          reader.onload = function () {
            imgResult = reader.result;
          };
          reader.onerror = function (error) {
            reject(error);
          };
          reader.onloadend = function () {
            resolve(imgResult);
          };
        });
      },
      //上传图
      uploadok:function(file){
        this.getBase64(file.raw).then((res) => {
          axios.post(this.IP_URL+'/addimage',{base64:res}).then((response)=>{
            if(response.data.errorcode == 0){
              this.imgurl = this.IP_URL+'/getimage?imgid='+response.data.img
              console.log(this.imgurl)
              this.$emit('getimgid',response.data.img)
            } else {
              this.$message.error(response.data.reason);
            }
          })
        });
        // /getimage？imgid=×××
      },
      showlog:function(val){
        this.act = val
        this.log = true
      },
      baocun:function(){
        this.$refs.cropper.getCropData(data => {
          // do something
          this.imgurl = data
          this.log = false
          console.log(data)
        })
        // this.$refs.cropper.getCropBlob(data => {
        //   // do something
        //   console.log(data)
        // })
      },




    }
  }
</script>


<style scoped lang="less">
  /deep/ .el-upload--text{ width: 100%; height: 100%;}

</style>
